package com.ck.controller.teacher;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.validation.Errors;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.ck.domain.Chapter;
import com.ck.domain.Paper;
import com.ck.service.ExamService;
import com.ck.service.QuestionService;

public class MakeUpPaperController extends SimpleFormController {
	
	private ExamService examService;
	private QuestionService questionService;
	
	//设置公共变量，供显示表单和回显表单时使用;
	private Integer examID = null;
	private List<Chapter> chapterList = null;
	
	public void setExamService(ExamService examService) {
		this.examService = examService;
	}

	public void setQuestionService(QuestionService questionService) {
		this.questionService = questionService;
	}

	@Override
	protected Map referenceData(HttpServletRequest request, Object command,
			Errors errors) throws Exception {
		
		Map model = new HashMap();
		examID = Integer.parseInt(request.getParameter("examID"));
		
		Integer subjectID = examService.gainExam(examID).getSubject();
		chapterList = questionService.gainChapterBySubject(subjectID);
		
		model.put("examID", examID);
		model.put("chapterList", chapterList);
		return model;
	}
	
	protected ModelAndView onSubmit(HttpServletRequest request,
			HttpServletResponse response, Object command, BindException errors)
			throws Exception {
		
		Paper paper = (Paper) command;
		Map model = errors.getModel();
		
		examID = Integer.parseInt(request.getParameter("examID"));
		
		//后台校验
		boolean flag = true;
		
		//试卷标题
		String title = paper.getTitle().trim();
		if(title == null || "".equals(title)) {
			model.put("error_title", "请输入试卷标题");
			flag = false;
		}
		if(title.length() > 60) {
			model.put("error_title", "试卷标题长度：1-60个字符");
			flag = false;
		}
		
		//覆盖率
		Integer coverageNum = Integer.parseInt(request.getParameter("count"));
		Integer[] chapterArray = new Integer[coverageNum];
		Integer[] percerntArray = new Integer[coverageNum];
		Integer total_percent = 0;
		for(int i=1; i<=coverageNum; i++){
			try {
				chapterArray[i-1] = Integer.parseInt(request.getParameter("chapter_"+i));
			} catch(Exception e){
				model.put("error_coverage", "章节没有正确选择！(第"+i+"行)");
				flag = false;
				break;
			}
			
			if( chapterArray[i-1]==0 || chapterArray[i-1]==null){
				model.put("error_coverage", "章节没有选择！(第"+i+"行)<br/>如果是多余的行,请点击“减”按钮删除.");
				flag = false;
				break;
			}
			
			try {
				percerntArray[i-1] = Integer.parseInt(request.getParameter("percent_"+i));
			} catch(Exception e){
				model.put("error_coverage", "百分比没有正确输入！(第"+i+"行)");
				flag = false;
				break;
			}
			
			if( percerntArray[i-1]==null ){
				model.put("error_coverage", "百分比没有输入！(第"+i+"行)<br/>如果是多余的行,请点击“减”按钮删除.");
				flag = false;
				break;
			}
			
			if( percerntArray[i-1]<1 || percerntArray[i-1]>100 ){
				model.put("error_coverage", "第"+i+"行的百分比超出限制！正确范围：1-100");
				flag = false;
				break;
			}
			
			total_percent = total_percent + percerntArray[i-1];
			//最后一次循环时检查总百分比
			if( i==coverageNum ){
				if( total_percent != 100 ){
					model.put("error_coverage", "百分比之和不等于100 ！");
					flag = false;
					break;
				}
			}
		}
		
		//平均难度
		Integer difficulty = paper.getDifficulty();
		if( difficulty == 0){
			model.put("error_difficulty", "请选择难度");
			flag = false;
		}
		
		//判断题数量
		Integer panduan_num = paper.getPanduan_num();
		if(panduan_num == null){
			model.put("error_panduan_num", "请输入判断题数量");
			flag = false;
		}else{
			if(panduan_num<1 || panduan_num>99){
				model.put("error_panduan_num", "判断题数量须为1-99的整数");
				flag = false;
			}
		}
		
		//选择题数量
		Integer xuanze_num = paper.getXuanze_num();
		if(xuanze_num == null){
			model.put("error_xuanze_num", "请输入选择题数量");
			flag = false;
		}else{
			if(xuanze_num<1 || xuanze_num>99){
				model.put("error_xuanze_num", "选择题数量须为1-99的整数");
				flag = false;
			}
		}
		
		//填空题数量
		Integer tiankong_num = paper.getTiankong_num();
		if(tiankong_num == null){
			model.put("error_tiankong_num", "请输入填空题数量");
			flag = false;
		}else{
			if(tiankong_num<1 || tiankong_num>99){
				model.put("error_tiankong_num", "填空题数量须为1-99的整数");
				flag = false;
			}
		}
		
		//总分
		Integer total_score = paper.getTotal_score();
		if(total_score == null){
			model.put("error_total_score", "请输入总分");
			flag = false;
		}else{
			if(total_score<1 || total_score>999){
				model.put("error_total_score", "总分须为1-999的整数");
				flag = false;
			}
		}
		try{
			if( total_score < (panduan_num + xuanze_num + tiankong_num) ){
				model.put("error_total_score", "总分不能小于题目总数！");
				flag = false;
			}
		} catch(Exception e){
			flag = false;
		}
		
		//备注
		String remark = paper.getRemark().trim();
		if( remark == null || "".equals(remark) ){
			paper.setRemark(null);
        }else{
        	if(remark.length() > 60) {
    			model.put("error_remark", "备注长度：0-60个字符");
    			flag = false;
    		}
        }

		//校验不通过
        if(!flag){
        	model.put("title", title);
        	model.put("difficulty", difficulty);
        	model.put("panduan_num", panduan_num);
        	model.put("xuanze_num", xuanze_num);
        	model.put("tiankong_num", tiankong_num);
        	model.put("total_score", total_score);
        	model.put("remark", remark);
        	model.put("examID", examID);
        	model.put("chapterList", chapterList);
			return new ModelAndView(getFormView(), model);
		}
		
		
		Integer teacherID = (Integer) request.getSession().getAttribute("teacherID");
		paper.setTeacher(teacherID);
		
		boolean makeUpSuccess = examService.makeUpPaper(paper, examID, chapterArray, percerntArray, model);
	
		if (makeUpSuccess) {
            return new ModelAndView(getSuccessView(),model);
        } else {
        	model.put("title", title);
        	model.put("difficulty", difficulty);
        	model.put("panduan_num", panduan_num);
        	model.put("xuanze_num", xuanze_num);
        	model.put("tiankong_num", tiankong_num);
        	model.put("total_score", total_score);
        	model.put("remark", remark);
        	model.put("examID", examID);
        	model.put("chapterList", chapterList);
            return new ModelAndView(getFormView(), model);
        }
	}

}
